package com.project.api.ym.dao;

import com.project.api.common.Unit;
import com.project.api.ym.model.Admin;
import com.project.api.ym.model.Roles;
import com.project.api.ym.model.Rules;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class RulesDao {
    @Autowired
    @Qualifier("mainJdbcTemplate")
    private JdbcTemplate mainJdbcTemplate;

    /**
     * 判断是否有超级权限
     * @param roles
     * @return
     */
    public boolean IsFullAuthByRoles(List<Roles> roles){
        boolean isFull=false;
        if (roles.size()<=0) return isFull;
        List<String> s = new ArrayList<>();
        for (Roles r : roles) {
            s.add(String.valueOf(r.getId()));
        }
        String role_list = "(" +String.join(",",s)+")";
        String sql = "SELECT b.* FROM "+ Roles.tableRolesRules +" a inner join " +Rules.tableName+" b on a.roles_id=b.id where a.roles_id in "+role_list+" and b.isfull=1";
        try {
            List<Map<String, Object>> list=mainJdbcTemplate.queryForList(sql);
            if(list.size()>0) isFull = true;
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
        }
        return isFull;
    }

    public boolean IsFullAuthByAdmin(List<Admin> admin){
        boolean isFull=false;
        if (admin.size()<=0) return isFull;
        List<String> s = new ArrayList<>();
        for (Admin r : admin) {
            s.add(String.valueOf(r.getId()));
        }
        String admin_list = "(" +String.join(",",s)+")";
        String sql = "SELECT c.* FROM "+ Admin.tableAdminRoles +" a inner join "+Roles.tableRolesRules+" b on a.roles_id=b.roles_id " +
                " inner join ym_rules c on b.rules_id=c.id " +
                " where a.admin_id in "+admin_list+" and c.isfull=1";
        try {
            List<Map<String, Object>> list=mainJdbcTemplate.queryForList(sql);
            if(list.size()>0) isFull = true;
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
        }
        return isFull;
    }
}
